﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Enums;
using CPlatePrintSys.Domain.Services;
using Prism.Dialogs;
using CPlatePrintSys.Infrastructure;

namespace CPlatePrintSys.Application.ViewModels
{
    public class UserAddOrEditViewModel : BindableBase, IDialogAware
    {
        private readonly IUserService _userService;
        private User _user;
        private User _originalUser;
        private User _currentUser;
        private bool _isEditMode;
        private string _confirmPassword;
        private string _errorMessage;
        private string _validationHint;

        public UserAddOrEditViewModel(IUserService userService, User currentUser = null)
        {
            _userService = userService;
            _currentUser = currentUser;
            User = new User();
            IsEditMode = false;

            // 初始化命令
            SaveCommand = new DelegateCommand(ExecuteSave, CanExecuteSave);
            CancelCommand = new DelegateCommand(ExecuteCancel);

            // 监听属性变化以更新命令状态
            PropertyChanged += OnPropertyChanged;
            
            // 初始化验证提示
            UpdateValidationHint();
        }

        public UserAddOrEditViewModel(IUserService userService, User user, User currentUser = null) : this(userService, currentUser)
        {
            if (user != null)
            {
                User = new User
                {
                    Id = user.Id,
                    Username = user.Username,
                    Password = user.Password,
                    JobNumber = user.JobNumber,
                    FullName = user.FullName,
                    Role = user.Role,
                    IsActive = user.IsActive,
                    CreatedAt = user.CreatedAt,
                    UpdatedAt = user.UpdatedAt,
                    LastLoginAt = user.LastLoginAt
                };
                IsEditMode = true;

                // 保存原始用户数据用于密码比较
                _originalUser = new User
                {
                    Id = user.Id,
                    Username = user.Username,
                    Password = user.Password,
                    JobNumber = user.JobNumber,
                    FullName = user.FullName,
                    Role = user.Role,
                    IsActive = user.IsActive,
                    CreatedAt = user.CreatedAt,
                    UpdatedAt = user.UpdatedAt,
                    LastLoginAt = user.LastLoginAt
                };
            }
        }

        public User User
        {
            get => _user;
            set => SetProperty(ref _user, value);
        }

        public bool IsEditMode
        {
            get => _isEditMode;
            set => SetProperty(ref _isEditMode, value);
        }

        //public string ConfirmPassword
        //{
        //    get => _confirmPassword;
        //    set => SetProperty(ref _confirmPassword, value);
        //}

        public string ErrorMessage
        {
            get => _errorMessage;
            set => SetProperty(ref _errorMessage, value);
        }

        public string ValidationHint
        {
            get => _validationHint;
            set => SetProperty(ref _validationHint, value);
        }

        /// <summary>
        /// 是否为超级管理员编辑自己的账号（只能修改密码）
        /// </summary>
        public bool IsSuperAdminEditingSelf => _currentUser != null && 
                                               _currentUser.Role == UserRole.SuperAdmin && 
                                               IsEditMode && 
                                               _currentUser.Id == User.Id;

        /// <summary>
        /// 用户名是否只读
        /// </summary>
        public bool IsUsernameReadOnly => IsSuperAdminEditingSelf;

        /// <summary>
        /// 姓名是否只读
        /// </summary>
        public bool IsFullNameReadOnly => IsSuperAdminEditingSelf;

        /// <summary>
        /// 工号是否只读
        /// </summary>
        public bool IsJobNumberReadOnly => IsSuperAdminEditingSelf;

        /// <summary>
        /// 角色是否只读
        /// </summary>
        public bool IsRoleReadOnly => IsSuperAdminEditingSelf;

        public List<UserRole> AvailableRoles
        {
            get
            {
                // 超级管理员可以创建管理员和普通用户
                if (_currentUser != null && _currentUser.Role == UserRole.SuperAdmin)
                {
                    if (IsEditMode && User.Role == UserRole.SuperAdmin)
                    {
                        // 编辑超级用户时，不显示角色选择（只读）
                        return new List<UserRole> { UserRole.SuperAdmin };
                    }
                    else
                    {
                        // 创建用户或编辑其他用户时，可以创建管理员和普通用户
                        return new List<UserRole> { UserRole.Admin, UserRole.User };
                    }
                }
               
                // 普通管理员只能创建普通用户
                return new List<UserRole> { UserRole.User };
            }
        }

        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(User.Username) || 
                e.PropertyName == nameof(User.Password) || 
                e.PropertyName == nameof(User.JobNumber) ||
                e.PropertyName == nameof(User.FullName))
            {
                ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged();
                UpdateValidationHint();
            }
        }

        private bool CanExecuteSave()
        {
            // 超级管理员编辑自己时，只验证密码
            if (IsSuperAdminEditingSelf)
            {
                return !string.IsNullOrWhiteSpace(User.Password) && IsValidPassword(User.Password);
            }

            // 基本验证
            if (string.IsNullOrWhiteSpace(User.Username) ||
                string.IsNullOrWhiteSpace(User.Password) ||
                string.IsNullOrEmpty(User.FullName) ||
                string.IsNullOrWhiteSpace(User.JobNumber))
            {
                return false;
            }

            // 用户名验证：3-10位英文字符
            if (!IsValidUsername(User.Username))
            {
                return false;
            }

            // 密码验证：6-20位字符
            if (!IsValidPassword(User.Password))
            {
                return false;
            }

            // 长度验证
            if (User.JobNumber.Length > 20 || User.FullName.Length > 100)
            {
                return false;
            }

            //// 编辑模式下不需要确认密码，新增模式下需要确认密码
            //if (!IsEditMode && string.IsNullOrWhiteSpace(ConfirmPassword))
            //{
            //    return false;
            //}

            //// 新增模式下密码确认验证
            //if (!IsEditMode && User.Password != ConfirmPassword)
            //{
            //    return false;
            //}

            return true;
        }

        private async void ExecuteSave()
        {
            try
            {
                ErrorMessage = string.Empty;

                // 验证输入数据
                var validationResult = ValidateUserInput();
                if (!validationResult.IsValid)
                {
                    ErrorMessage = validationResult.ErrorMessage;
                    return;
                }

                // 验证用户名、工号、密码不能重复
                var existingUsers = await _userService.GetAllUsersAsync();
                
                // 检查用户名重复
                if (existingUsers.Any(u => u.Username.Equals(User.Username, StringComparison.OrdinalIgnoreCase) && u.Id != User.Id))
                {
                    ErrorMessage = "用户名已存在，请使用其他用户名";
                    return;
                }

                // 检查工号重复
                if (existingUsers.Any(u => u.JobNumber.Equals(User.JobNumber, StringComparison.OrdinalIgnoreCase) && u.Id != User.Id))
                {
                    ErrorMessage = "工号已存在，请使用其他工号";
                    return;
                }

                // 密码重复检查已移除，允许多个账号使用同一密码

                //// 加密密码（仅在新增模式或密码已更改时）
                //if (!IsEditMode)
                //{
                //    User.Password = HashPassword(User.Password);
                //}
                //else if (!string.IsNullOrEmpty(User.Password) && User.Password != _originalUser.Password)
                //{
                //    // 编辑模式下，只有当密码确实改变时才重新加密
                //    User.Password = HashPassword(User.Password);
                //}

                if (IsEditMode && ((!string.IsNullOrEmpty(User.Password)) && User.Password != _originalUser.Password))
                {
                    // 编辑模式下，只有当密码确实改变时才重新加密
                    User.Password = Utilities.HashPassword(User.Password);
                }

                // 设置更新时间
                User.UpdatedAt = DateTime.Now;

                if (IsEditMode)
                {
                    await _userService.UpdateUserAsync(User);
                }
                else
                {
                    User.CreatedAt = DateTime.Now;
                    await _userService.CreateUserAsync(User);
                }

                // 关闭对话框并返回结果
                var result = new DialogResult(ButtonResult.OK);
                result.Parameters.Add("User", User);
                RequestClose?.Invoke(result);
            }
            catch (Exception ex)
            {
                ErrorMessage = $"保存失败: {ex.Message}";
            }
        }

        public void InvokeRaiseUpdate(string password)
        {
           // this.ConfirmPassword = password;
            ((DelegateCommand)SaveCommand).RaiseCanExecuteChanged();
            UpdateValidationHint();
        }

        private void ExecuteCancel()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
        }


        #region Validation Methods

        /// <summary>
        /// 更新验证提示信息
        /// </summary>
        private void UpdateValidationHint()
        {
            var hints = new List<string>();

            // 超级管理员编辑自己时，只检查密码
            if (IsSuperAdminEditingSelf)
            {
                if (string.IsNullOrWhiteSpace(User.Password))
                {
                    hints.Add("请输入密码");
                }
                else if (!IsValidPassword(User.Password))
                {
                    hints.Add("密码必须为6-20位字符");
                }
            }
            else
            {
                // 检查用户名
                if (string.IsNullOrWhiteSpace(User.Username))
                {
                    hints.Add("请输入登录账号");
                }
                else if (!IsValidUsername(User.Username))
                {
                    hints.Add("登录账号必须为3-10位英文字符");
                }

                // 检查密码
                if (string.IsNullOrWhiteSpace(User.Password))
                {
                    hints.Add("请输入密码");
                }
                else if (!IsValidPassword(User.Password))
                {
                    hints.Add("密码必须为6-20位字符");
                }

                // 检查姓名
                if (string.IsNullOrWhiteSpace(User.FullName))
                {
                    hints.Add("请输入姓名");
                }
                else if (User.FullName.Length > 100)
                {
                    hints.Add("姓名长度不能超过100个字符");
                }

                // 检查工号
                if (string.IsNullOrWhiteSpace(User.JobNumber))
                {
                    hints.Add("请输入工号");
                }
                else if (User.JobNumber.Length > 20)
                {
                    hints.Add("工号长度不能超过20个字符");
                }
            }

            ValidationHint = hints.Count > 0 ? string.Join("；", hints) : string.Empty;
        }

        /// <summary>
        /// 验证用户名：3-10位英文字符
        /// </summary>
        private bool IsValidUsername(string username)
        {
            if (string.IsNullOrWhiteSpace(username))
                return false;

            // 检查长度：3-10位
            if (username.Length < 3 || username.Length > 10)
                return false;

            // 检查是否只包含英文字符
            return username.All(c => char.IsLetter(c));
        }

        /// <summary>
        /// 验证密码：6-20位字符
        /// </summary>
        private bool IsValidPassword(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
                return false;

            // 检查长度：6-20位
            return password.Length >= 6 && password.Length <= 20;
        }

        /// <summary>
        /// 验证用户输入数据
        /// </summary>
        private ValidationResult ValidateUserInput()
        {
            // 基本验证
            if (string.IsNullOrWhiteSpace(User.Username))
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "请输入登录账号" };
            }

            if (string.IsNullOrWhiteSpace(User.Password))
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "请输入密码" };
            }

            if (string.IsNullOrWhiteSpace(User.FullName))
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "请输入姓名" };
            }

            if (string.IsNullOrWhiteSpace(User.JobNumber))
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "请输入工号" };
            }

            // 用户名验证：3-10位英文字符
            if (!IsValidUsername(User.Username))
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "登录账号必须为3-10位英文字符" };
            }

            // 密码验证：6-20位字符
            if (!IsValidPassword(User.Password))
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "密码必须为6-20位字符" };
            }

            // 其他长度验证
            if (User.JobNumber.Length > 20)
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "工号长度不能超过20个字符" };
            }

            if (User.FullName.Length > 100)
            {
                return new ValidationResult { IsValid = false, ErrorMessage = "姓名长度不能超过100个字符" };
            }

            return new ValidationResult { IsValid = true };
        }

        /// <summary>
        /// 验证结果类
        /// </summary>
        private class ValidationResult
        {
            public bool IsValid { get; set; }
            public string ErrorMessage { get; set; }
        }

        #endregion

        #region IDialogAware Implementation
        public string Title => IsEditMode ? "编辑用户" : "添加用户";

        DialogCloseListener IDialogAware.RequestClose => throw new NotImplementedException();

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog() => true;

        public void OnDialogClosed()
        {
            // 清理资源
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            // 对话框打开时的初始化
        }
        #endregion
    }
}

